package com.msconfig.mvp.view.activity.base;

/*
 * author: caojunhao
 * date  : 2020/4/28
 * desc  :
 */

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseMvpFragment extends BaseFragment implements BaseView {
    public List<BasePresenter> mPresenters;
    public Context context;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        inintPresenter();
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    private void inintPresenter() {
        //初始化Presenter
        if (mPresenters == null) {
            mPresenters = new ArrayList<>();
        }
        createPresenter(mPresenters);
        //presenter与View绑定
        if (null != mPresenters) {
            for (BasePresenter presenter : mPresenters) {
                presenter.attachView(this);
            }
        }
    }

    protected abstract void createPresenter(List<BasePresenter> mPresenters);


    @Override
    public void onDestroyView() {
        detachPresenter();
        super.onDestroyView();
    }

    private void detachPresenter() {
        //presenter与activity解绑定
        if (null != mPresenters) {
            while (!mPresenters.isEmpty()) {
                BasePresenter presenter = mPresenters.get(0);
                presenter.detachView();
                mPresenters.remove(0);
            }
        }
    }


    /**
     * fragment退栈
     */
    public void backTo() {
        if (getBackStackCount() > 0)
            popBackStack();
        else
            getActivity().finish();
    }

    /**
     * 获取栈数
     * @return
     */
    protected int getBackStackCount() {
        try {
            return getFragmentManager().getBackStackEntryCount();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 退栈事务回滚
     */
    protected void popBackStack() {
        getFragmentManager().popBackStackImmediate();
    }

    /**
     * 回退n层栈
     */
    protected void backToHome(){
        final FragmentManager fragmentManager = getFragmentManager();
        while (fragmentManager.getBackStackEntryCount() != 0) {
            fragmentManager.popBackStackImmediate();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;
    }

    @Override
    public void showToast(int resId) {
        Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
    }
}
